package com.lanou3g.HW_0514;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by dllo on 18/5/14.
 */
@WebServlet(name = "RegisterServlet", urlPatterns = "/c")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 拿数据
        String username = request.getParameter("username");
        String pwd = request.getParameter("password");
        // 校验
        boolean starWithNum = false;
        for (int i = 0; i < 9; i++) {
            if (username.startsWith(String.valueOf(i))) {
                starWithNum = true;
            }
        }

        // 根据校验结果的不同,显示不同结果
        RequestDispatcher rd = null;
        if (starWithNum) {
            System.out.println("注册失败,用户名不能以数字开头");

        } else {

            String sql = "INSERT INTO users (username, pwd)" +
                    " VALUES (" +
                    "'" + username + "',"
                    + "'" + pwd + "')";
            Statement statement = JDBCUtil.getStatement();
            try {
                int rows = statement.executeUpdate(sql);
                if (rows > 0) {
                    System.out.println("注册成功");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);
    }
}
